package tool

import (
	"github.com/dgrijalva/jwt-go"
)

var mySigningKey = []byte("jwt-secret")

type MyClaims struct {
	jwt.StandardClaims
	Username string `json:"username"`
}

func GenerateToken(username string) (string, error) {
	var claim = MyClaims{
		Username: username,
		StandardClaims: jwt.StandardClaims{
			Issuer: "admin",
		},
	}
	token := jwt.NewWithClaims(jwt.SigningMethodHS256, claim)
	tokenString, err := token.SignedString(mySigningKey)
	return tokenString, err
}

// 解析token
func ParseToken(tokenString string) string {
	token, err := jwt.ParseWithClaims(tokenString, &MyClaims{}, func(token *jwt.Token) (interface{}, error) {
		return mySigningKey, nil
	})
	if err != nil {
		return ""
	}
	var username string
	if claims, ok := token.Claims.(*MyClaims); ok && token.Valid {
		username = claims.Username
	}
	return username
}
